import express from 'express'
import sqlQuery from '../utils/sql';
import randomNum from '../utils/random';
import { v4 } from 'uuid';
import { isTimeout,getTime } from '../utils/decodeTime';
const router = express.Router()
const Core = require('@alicloud/pop-core');
var client = new Core({
  accessKeyId: 'LTAI5tEz4zAWBWL9vt8YfiP5',
  accessKeySecret: 'E1PCeoHKKtnQtsvopNvCr8I19zGNSE',
  endpoint: 'https://dysmsapi.aliyuncs.com',
  apiVersion: '2017-05-25'
});
// 获取验证码
router.post('/sendcode', (request, response) => {
  const {phone} = request.body 
  const TemplateParam = {code:randomNum()}
  var params = {
    "SignName": "阿里云短信测试",
    "TemplateCode": "SMS_154950909",
    "PhoneNumbers": `${phone}`,
    "TemplateParam": JSON.stringify(TemplateParam)
  }
  
  const requestOption = {
    method: 'POST',
    formatParams: false,
  };
  client.request('SendSms', params, requestOption).then((result) => {
    response.send({
      code:200,
      verifycode:TemplateParam,
      msg:'二维码发送成功'
    })
  }, (ex) => {
    response.send({
      code:404,
      msg:'二维码发送错误'
    })
  })
})
// 向数据库添加验证码
router.post('/addVerifycode',async (request,response)=>{
  let {phone,verifycode} = request.body 
  await sqlQuery(`insert into verifycode values ('${v4()}','${verifycode}','${phone}','${getTime(new Date())}')`)
  response.send({
    code:200,
    msg:'数据库添加成功'
  })
})
// 比较验证码的真伪
router.post('/compareVerifycode',async (request,response)=>{
  let {phone,verifycode} = request.body  
  let res = await sqlQuery(`select * from verifycode where phone = '${phone}' and code = '${verifycode}'`)
  let user = await sqlQuery(`select * from  user where phone = '${phone}'`)
  if(res.length === 1){
    let flag = isTimeout(res[0].createtime,1000 * 60 * 1000000 * 24)
    if(flag){
      response.send({
        code:200,
        msg:'success',
        user
        
      })
    }else{
      response.send({
        code:304,
        msg:'验证码超时无效'
      })
    }
  }else{
    response.send({
      code:404,
      msg:'验证码错误'
    })
  }
})
export default router





